package com.coscoshipping.rams.demo.controller;

import com.coscoshipping.rams.demo.pojo.vo.BusinessSalesVO;
import com.coscoshipping.rams.demo.pojo.vo.TicketSalesVO;
import com.coscoshipping.rams.demo.service.ITicketSalesStatisticsService;
import com.coscoshipping.rams.demo.utils.HttpUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 票型销售统计表 前端控制器
 * </p>
 *
 * @author zhaoyin.yang
 * @since 2025-04-19
 */
@Slf4j
@Tag(name = "票型销售统计信息表")
@Validated
@RestController
@RequestMapping("/ticketSalesStatistics")
public class TicketSalesStatisticsController {

    @Autowired
    private ITicketSalesStatisticsService ticketSalesStatisticsService;


    @Operation(summary = "指定日期段同步数据到数据库")
    @GetMapping("/syncData")
    @ResponseBody
    public String syncData(@RequestParam(name = "startDate") @Parameter(description = "开始日期，格式为 yyyy-MM-dd") LocalDate startDate,
                           @RequestParam(name = "endDate") @Parameter(description = "结束日期，格式为 yyyy-MM-dd") LocalDate endDate) {
        try {

            // 使用 for 循环遍历日期范围
            for (startDate = startDate; !startDate.isAfter(endDate); startDate = startDate.plusDays(1)) {
                // 调用 HttpUtils 获取数据
                List<TicketSalesVO> response = HttpUtils.ticketSales(startDate.atStartOfDay());

                // 将数据保存到数据库
                ticketSalesStatisticsService.saveOrUpdateData(response);
            }
            return "数据同步成功";
        } catch (Exception e) {
            log.error("数据同步失败", e);
            return "数据同步失败: " + e.getMessage();
        }
    }


    /**
     * 指定日期同步数据到数据库
     */
    @Operation(summary = "指定日期同步数据到数据库")
    @GetMapping("/syncDataByDay")
    @ResponseBody
    public String syncDataByDay(@RequestParam(name = "date")
                                @Parameter(description = "下单时间，格式为 yyyy-MM-dd")
                                LocalDate date) {
        try {
            // 调用 HttpUtils 获取数据
            List<TicketSalesVO> response = HttpUtils.ticketSales(date.atStartOfDay());

            // 将数据保存到数据库
            ticketSalesStatisticsService.saveOrUpdateData(response);
            return "数据同步成功";
        } catch (Exception e) {
            log.error("数据同步失败", e);
            return "数据同步失败: " + e.getMessage();
        }
    }
}